package com.share.shop.h5.web.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.share.common.common.Result;
import com.share.common.utils.UUIDUtil;
import com.share.config.ali.pay.AliPay;
import com.share.config.ali.pay.AliPayProperties;
import com.share.config.ali.pay.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pay")
public class ZfbPayController {

    @Autowired
    private AliPayProperties properties;

    @Autowired
    private AliPay aliPay;


    /**
     * 用户下单:支付宝支付
     * 1、让支付页让浏览器展示
     * 2、支付成功以后，跳转到用户的订单列表页
     *
     * @param orderCode 订单编码
     * @return
     * @throws AlipayApiException
     */
    @ResponseBody
    @GetMapping(value = "/payOrder", produces = "text/html")
    public Result aliPayOrder(@RequestParam String orderCode) {
        // 通过订单编码查询支付信息
        String tradeNo = UUIDUtil.genUUId();
        try {
            String res = aliPay.pay(tradeNo, "99.8", "88充值", "小米给我充值");
            return Result.success(res);
        } catch (AlipayApiException e) {
            log.error("调用异常", e);
            return Result.failure(e.getErrMsg());
        }
    }

    @GetMapping(value = "/pay/syncNotify")
    public String paySyncNotify(PayAsyncVo payasyncVo, HttpServletRequest request) {
        log.info("同步通知内容：" + payasyncVo);
        return "paySuccess";
    }

    /**
     * 支付宝的异步通知,只要返回 success 支付宝便不再通知
     */
    @PostMapping(value = "/pay/asyncNotify")
    @ResponseBody
    public String payAsyncNotify(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException {
        // 获取支付宝反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getPublicKey(), properties.getCharset(), properties.getSignType());

        if (signVerified) {
            log.info("签名验证成功...");
            // 业务处理，如修改订单状态
            log.info(asyncVo.toString());

            return "success";
        } else {
            log.info("签名验证失败...");
            return "error";
        }
    }
}

